package strrpos

import (
	"strings"
)

// https://www.php.net/manual/zh/function.strrpos.php
func Do(haystack string, needle string, offset int) int {
    result := -1
	if haystack == "" || needle == ""{
		return result
	}
	length := len(haystack)
    if offset > length || offset + length < 0{
        return result
    } 
    if offset > 0{
        haystack = haystack[offset:]
    } else if offset < 0{
        first := needle[:1]
        firstNum := strings.LastIndex(haystack[:(offset+length+1)],first)
        if firstNum == -1{
            return result;
        }
        firstLength := firstNum + len(needle)
        if firstLength > length{
            firstLength = length
        }
        haystack = haystack[:firstLength]
        offset = 0;
    }
    judge := strings.LastIndex(haystack,needle)
    if judge >= 0{
        result = judge + offset
    }
    return result
}